package art_of_java_concurrent_programming.lock.stamped_lock;

import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.StampedLock;

/**
 * @author lixiangke
 * @date 2018/12/21
 */
public class StampedLockCpuDemo {
    private static Thread[] holdCpuThreads = new Thread[3];
    private static final StampedLock stampedLock = new StampedLock();

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            long lockw = stampedLock.writeLock();
            // park 函数在遇到线程中断时，会直接返回，不会抛出异常
            LockSupport.parkNanos(6000000000000L);
            stampedLock.unlockWrite(lockw);
        }).start();

        Thread.sleep(100);

        for (int i = 0; i < 3; i++) {
            holdCpuThreads[i] = new Thread(new HoldCpuReadThread());
            holdCpuThreads[i].start();
        }

        Thread.sleep(10000);

        for (int i = 0; i < 3; i++) {
            holdCpuThreads[i].interrupt();
        }
    }

    private static class HoldCpuReadThread implements Runnable {

        @Override
        public void run() {
            long lockr = stampedLock.readLock();
            System.out.println(Thread.currentThread().getName() + "获得读锁");
            stampedLock.unlockRead(lockr);
        }
    }
}
